import React, { useState, useEffect } from 'react';
import { Table, Popconfirm, Form, Input, Button, Select, Modal, Empty, Row, Col, message, Spin, Typography } from 'antd';
import { EyeOutlined, EditOutlined, DeleteOutlined, PlusOutlined, SearchOutlined, Loading3QuartersOutlined, CloseOutlined } from '@ant-design/icons';
import './index.less';
import { http } from '../../utils/httpClient';

interface DocumentItem {
    key: string;
    name: string;
    type: 'file' | 'folder';
    size?: string;
    modified: string;
    tags?: string[];
}
const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 }
    }
};
const KnowledgeManagement: React.FC = () => {
    const [itemsData, setItemsData] = useState<any[]>([]);// 数据源下拉菜单
    const [items, setItems] = useState('');// 默认第一个数据源
    const [form] = Form.useForm();
    // 新增状态管理选中项
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [selectedRows, setSelectedRows] = useState<any[]>([]);

    // 配置表格行选择功能
    const rowSelection = {
        selectedRowKeys,
        onChange: (selectedKeys: React.Key[], selectedRows: any[]) => {
            setSelectedRowKeys(selectedKeys);
            setSelectedRows(selectedRows);
        },
    };
    const [loading, setLoading] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const [modalType, setModalType] = useState<'create' | 'edit' | 'view'>('create');
    const [currentRecord, setCurrentRecord] = useState<any>(null);
    const [searchParams, setSearchParams] = useState({
        name: '',
        source: items,
    })// 查询条件

    // 初始化加载列表
    useEffect(() => {
        setLoading(true)
        getSourceList() // 数据源下拉菜单
    }, []);
    // 数据源下拉菜单
    const getSourceList = () => {
        http.post(`${window.config.API_BASE_URL}/chatbiv3/ds/available`, { user: 'tiantian' })
            .then((res: any) => {
                if (res.status_code == '200' && res.available ?.length) {
                    setItemsData(res.available);
                    setItems(res.available[0])
                    getList(res.available[0])
                }
            })
            .finally(() => setLoading(false));
    }
    // 列表
    const getList = (items: any) => {
        setLoading(true)
        http.post(`http://8.140.229.23:8576/dataManagement/knowledge/view`, { user: 'tiantian', source: items })
            .then((res: any) => {
                if (res.status_code == '100') {
                    setDocuments(res.knowledge);
                    setLoading(false)
                }
            })
            .finally(() => setLoading(false));
    };
    // 模拟文档数据
    const [documents, setDocuments] = useState<DocumentItem[]>([]);
    // 单个删除
    const handleDelete = (record: any) => {
        console.log(record);
        http.post(`http://8.140.229.23:8576/dataManagement/knowledge/delete`, { user: 'tiantian', chunk_id: record.chunk_id })
            .then((res: any) => {
                if (res.status_code == '200') {
                    setLoading(true)
                    getList(items); // 刷新数据
                    messageApi.open({
                        type: 'success',
                        content: res.status_msg
                    });
                }
            })
            .finally(() => setLoading(false));
    };

    // 批量删除处理函数
    const handleBatchDelete = async () => {
        if (selectedRowKeys.length === 0) {
            messageApi.warning('请至少选择一项进行删除');
            return;
        }
        try {
            setLoading(true);
            // 构造符合要求的参数数组
            http.post(`http://8.140.229.23:8576/dataManagement/knowledge/delete`,
                {
                    user: 'tiantian',
                    chunk_id: selectedRowKeys // 直接使用选中的 keys 数组
                }
            )
                .then((res: any) => {
                    if (res.status_code === 200) {
                        messageApi.success(`成功删除 ${selectedRowKeys.length} 项`);
                        getList(items); // 刷新数据
                        setSelectedRowKeys([]); // 清空选中状态
                    }
                })
                .finally(() => setLoading(false));

        } catch (error) {
            // messageApi.error(`删除失败: ${error.message}`);
        } finally {
            setLoading(false);
        }
    };

    // 查询处理
    const handleSearch = () => {
        getList(searchParams.source || items)
    };

    // 打开弹窗
    const showModal = (type: 'create' | 'edit' | 'view', record?: any) => {
        setModalType(type);
        setModalVisible(true);
        if (record) {
            setCurrentRecord(record);
            form.setFieldsValue(record);
        } else {
            form.resetFields();
        }
    };
    // 提交表单
    const [messageApi, contextHolder] = message.useMessage();
    const [confirmLoading, setConfirmLoading] = React.useState(false);
    const handleSubmit = () => {
        form.submit();
    };
    const onFinish = (value: any) => {
        console.log(value);
        postData(value);
    };
    const postData = (value: any) => {
        setConfirmLoading(true);
        const db_configs = {
            "user": 'tiantian',
            "source": value.source,
            "content": value.content,
            "explain": value.explain,
            "sql": value.sql,
        }
        http.post(`http://8.140.229.23:8576/dataManagement/knowledge/add`, db_configs)
            .then((res: any) => {
                if (res.status_code == 100) {
                    setConfirmLoading(false);
                    setModalVisible(false);
                    getList(value.source)
                    messageApi.open({
                        type: 'success',
                        content: res.status_msg
                    });
                    form.resetFields();
                } else {
                    messageApi.open({
                        type: 'warning',
                        content: res.result
                    });
                }
            })
            .finally(() => setLoading(false));
    };

    // 表格列配置
    const columns = [
        { title: 'id', dataIndex: 'chunk_id', key: 'chunk_id' },
        { title: '知识标题', dataIndex: 'content', key: 'content' },
        // { title: '用户名', dataIndex: 'user', key: 'user' },
        { title: '数据源', dataIndex: 'source', key: 'source' },
        { title: '业务知识内容', dataIndex: 'explain', key: 'explain' },
        { title: '参照的SQL信息', dataIndex: 'sql', key: 'sql' },
        // { title: '描述', dataIndex: 'desc', key: 'desc', ellipsis: true },
        {
            title: '操作',
            key: 'action',
            render: (_: any, record: { key: string; }) => (
                <div className="action-buttons">
                    <Button
                        size="small"
                        type="link"
                        icon={<EyeOutlined />}
                        onClick={() => showModal('view', record)}
                    >
                    </Button>
                    <Button
                        size="small"
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => showModal('edit', record)}
                    >
                    </Button>
                    <Popconfirm
                        title="确定删除该知识库吗？"
                        onConfirm={() => handleDelete(record)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button size="small" type="link" danger icon={<DeleteOutlined />}>
                        </Button>
                    </Popconfirm>
                </div>
            )
        }
    ];

    return (
        <div className="knowledgeManagement">
            {contextHolder}
            <div className="dataSource">
                <h2>知识管理</h2>
                <h4 style={{ color: '#8c8c8c' }}>知识管理</h4>
                {/* 查询条件 */}
                <Form layout="inline">
                    <Row gutter={16} style={{ width: '100%' }}>
                        <Col span={6}>
                            <Form.Item label="">
                                <Input
                                    placeholder="请输入名称"
                                    allowClear
                                    onChange={e => setSearchParams({ ...searchParams, name: e.target.value })}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={6}>
                            <Form.Item label="">
                                <Select
                                    placeholder="请选择数据源"
                                    allowClear
                                    value={items} // 安全访问
                                    onChange={e => {
                                        console.log(e);
                                        setItems(e)
                                        setSearchParams({ ...searchParams, source: e })
                                    }}
                                >
                                    {itemsData.map((item) => (
                                        <Select.Option key={item} value={item}>{item}</Select.Option>
                                    ))}
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={12}
                            style={{ textAlign: 'right' }}
                        >
                            <Button
                                type="primary"
                                icon={<SearchOutlined />}
                                onClick={handleSearch}
                                style={{ marginRight: 16 }}
                            >
                                查询
                                </Button>
                            <Button
                                type="primary"
                                icon={<Loading3QuartersOutlined />}
                                onClick={handleSearch}
                                style={{ marginRight: 16 }}
                            >
                                刷新
                                </Button>
                            <Button
                                danger
                                icon={<DeleteOutlined />}
                                onClick={handleBatchDelete}
                                disabled={!selectedRowKeys.length}
                                style={{ marginRight: 16 }}
                            >
                                删除选中项 ({selectedRowKeys.length})
                                </Button>
                            {selectedRowKeys.length > 0 && (
                                <Button onClick={() => setSelectedRowKeys([])} style={{ marginRight: 16 }}>
                                    <CloseOutlined /> 清空选择
                                </Button>
                            )}
                            <Button
                                type="primary"
                                icon={<PlusOutlined />}
                                onClick={() => showModal('create')}
                            >
                                新建
                            </Button>
                        </Col>
                    </Row>
                </Form>
                {/* 主要内容区域 */}
                <div style={{ margin: '20px 0' }}>
                    <Spin tip="加载中..." spinning={loading}>
                        <Table
                            rowKey="chunk_id" // 根据你的数据唯一标识字段调整，例如 id 或其他唯一值
                            rowSelection={{
                                type: 'checkbox',
                                selectedRowKeys,
                                onChange: setSelectedRowKeys,
                            }}
                            dataSource={documents}
                            columns={columns}
                            rowClassName={() => 'document-row'}
                            pagination={{ pageSize: 10 }}
                            locale={{
                                emptyText: (
                                    <Empty
                                        description={false}
                                    />
                                )
                            }}
                        />
                    </Spin>
                </div>
                {/* 弹窗表单 */}
                <Modal title={`${{
                    create: '新建知识库',
                    edit: '编辑知识库',
                    view: '查看知识库'
                }[modalType]}`} open={modalVisible} confirmLoading={confirmLoading} onOk={handleSubmit} onCancel={() => setModalVisible(false)}
                    okText="确定" cancelText="取消"
                    footer={modalType === 'view' ? null : undefined}
                >
                    <Form {...formItemLayout} form={form} variant={'filled'} style={{ maxWidth: 600, padding: 24 }} initialValues={{ variant: 'filled' }} onFinish={onFinish}>
                        <Form.Item label="知识标题" name="content" rules={[{ required: true, message: '请输入知识标题!' }]}>
                            <Input placeholder="请输入知识标题" disabled={modalType === 'view'} />
                        </Form.Item>

                        <Form.Item label="数据源" name="source" rules={[{ required: true, message: '请输入数据源!' }]}>
                            <Select
                                placeholder="请选择数据源"
                                allowClear
                                disabled={modalType === 'view'}
                            >
                                {itemsData.map((item) => (
                                    <Select.Option value={item}>{item}</Select.Option>
                                ))}
                            </Select>
                        </Form.Item>

                        <Form.Item label="业务知识内容" name="explain" rules={[{ required: true, message: '请输入业务知识内容!' }]}>
                            <Input placeholder="请输入业务知识内容" disabled={modalType === 'view'} />
                        </Form.Item>

                        <Form.Item label="参照的SQL信息" name="sql" rules={[{ required: true, message: '请输入参照的SQL信息!' }]}>
                            <Input placeholder="请输入参照的SQL信息" disabled={modalType === 'view'} />
                        </Form.Item>
                    </Form>

                </Modal>
            </div>
        </div >
    );
};

export default KnowledgeManagement;